# api/views.py
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from .models import User
from .serializers import UserSerializer
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.parsers import JSONParser
from django.db.models import Q
from django.conf import settings

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    parser_classes = [JSONParser, FormParser, MultiPartParser]
    @action(methods=['post'], detail=False, url_path='login')
    def login(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        try:
            user = User.objects.get(username=username, password=password)
            token = '1741f74aed758a688515f72572dc8e37'  # 生成token的逻辑
            return Response({'code': 0, 'message': '登录成功', 'data': {'userId': user.id, 'token': token}})
        except User.DoesNotExist:
            return Response({'code': 1, 'message': '用户名或密码错误'})

    @action(methods=['post'], detail=False, url_path='register')
    def register(self, request):
        serializer = UserSerializer(data=request.data)
        print(serializer)
        if serializer.is_valid():
            serializer.save()
            return Response({'code': 0, 'message': '注册成功'})
        return Response(serializer.errors)

    @action(methods=['get'], detail=False, url_path='getUserInfo')  
    def getUserInfo(self, request):  
        username = request.query_params.get('username')  
        if not username:  
            return Response({'code': 1, 'message': '用户名不能为空'}, status=status.HTTP_400_BAD_REQUEST)  
  
        try:  
            user = User.objects.get(username=username)  
            serializer = UserSerializer(user)  
            data = serializer.data  
            return Response({'code': 0, 'message': '获取用户信息成功', 'data': data})  
        except User.DoesNotExist:  
            return Response({'code': 2, 'message': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)

    
    @action(methods=['get'], detail=True, url_path='getUserDetail')
    def get_user_detail(self, request, pk=None):  
        try:
            user = User.objects.get(pk=pk)
            serializer = UserSerializer(user)
            return Response({'code': 0, 'message': '获取用户信息成功', 'data': serializer.data})
        except User.DoesNotExist:
            return Response({'code': 1, 'message': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)

    @action(methods=['put'], detail=False, url_path='updateUser')
    def update_user(self, request):
        # 从请求数据中获取用户ID
        print(request.data)
        user_id = request.data.get('id')
        if not user_id:
            return Response({'code': 1, 'message': '用户ID不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取用户实例
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({'code': 1, 'message': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)

        # 创建序列化器实例，并传入用户实例和请求数据
        serializer = UserSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 0,
                'message': '编辑用户成功',
                'data': UserSerializer(user).data
            })
        return Response({'code': 2, 'message': '参数错误', 'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
    
    @action(methods=['get'], detail=False, url_path='getUserList')
    def getUserList(self, request):
        username = request.query_params.get('username')
        nickname = request.query_params.get('nickname')
        gender = request.query_params.get('gender')
        role = request.query_params.get('role')

        # 创建一个空的Q对象用于过滤
        filtered_users = Q()

        # 如果有提供查询参数，则添加到过滤条件中
        if username:
            filtered_users &= Q(username__icontains=username)
        if nickname:
            filtered_users &= Q(nickname__icontains=nickname)
        if gender:
            filtered_users &= Q(gender=gender)
        if role:
            filtered_users &= Q(is_admin=(role == '1'))  # 假设is_admin字段表示角色

        # 应用过滤条件
        users = self.queryset.filter(filtered_users).distinct()

        # 序列化用户对象
        serializer = UserSerializer(users, many=True)

        # 返回序列化后的数据
        return Response({
            'code': 0,
            'message': '获取用户列表成功',
            'data': serializer.data
        })


    @action(methods=['delete'], detail=False, url_path='deleteUser')
    def deleteUser(self, request):
        ids = request.data.get('ids')
        if not ids:
            return Response({'code': 1, 'message': '请选择要删除的用户'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            deleted_count = User.objects.filter(id__in=ids).delete()[0]
            return Response({
                'code': 0,
                'message': f'成功删除了{deleted_count}个用户',
                'data': self.get_serializer(self.get_queryset(), many=True).data
            })
        except Exception as e:
            return Response({'code': 2, 'message': f'删除用户失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


    @action(methods=['post'], detail=False, url_path='addUser')
    def addUser(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            return Response({
                'code': 0,
                'message': '新增用户成功',
                'data': UserSerializer(user).data
            })
        return Response({'code': 1, 'message': '参数错误', 'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
# api/views.py
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django.utils import timezone
from .models import Topic
from .serializers import TopicSerializer

class TopicViewSet(viewsets.ModelViewSet):
    queryset = Topic.objects.all()
    serializer_class = TopicSerializer
    parser_classes = [JSONParser, FormParser, MultiPartParser]  # 添加解析器以处理文件上传

    @action(methods=['get'], detail=False, url_path='getTopicList')
    def getTopicList(self, request):
        t_uid = request.query_params.get('t_uid')
        t_title = request.query_params.get('t_title')
        t_kind = request.query_params.get('t_kind')

        filtered_topics = Q()
        if t_uid:
            filtered_topics &= Q(t_uid=t_uid)
        if t_title:
            filtered_topics &= Q(t_title__icontains=t_title)
        if t_kind:
            filtered_topics &= Q(t_kind=t_kind)

        topics = self.queryset.filter(filtered_topics).distinct()
        serializer = TopicSerializer(topics, many=True)
        return Response({
            'code': 0,
            'message': '获取帖子列表成功',
            'data': serializer.data
        })

    @action(methods=['get'], detail=True, url_path='getTopicDetail')
    def getTopicDetail(self, request, pk=None):
        try:
            topic = Topic.objects.get(pk=pk)
            serializer = TopicSerializer(topic)
            return Response({
                'code': 0,
                'message': '获取帖子详情成功',
                'data': serializer.data
            })
        except Topic.DoesNotExist:
            return Response({'code': 1, 'message': '帖子不存在'}, status=status.HTTP_404_NOT_FOUND)

    @action(methods=['post'], detail=False, url_path='updateTopic')
    def updateTopic(self, request):
        # 从请求数据中获取t_id和t_uid
        print(request.data)
        t_id = request.data.get('id')
        t_uid = request.data.get('t_uid')

        # 检查t_id和t_uid是否存在
        if not t_id or not t_uid:
            return Response({'code': 2, 'message': '参数错误，缺少t_id或t_uid'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 获取帖子实例
            topic = Topic.objects.get(id=t_id, t_uid=t_uid)
        except Topic.DoesNotExist:
            return Response({'code': 1, 'message': '帖子不存在'}, status=status.HTTP_404_NOT_FOUND)

        # 使用序列化器更新帖子
        serializer = TopicSerializer(topic, data=request.data, partial=True)
        if serializer.is_valid():
            topic = serializer.save()
            return Response({
                'code': 0,
                'message': '编辑帖子成功',
                'data': TopicSerializer(topic).data
            })
        return Response({'code': 2, 'message': '参数错误', 'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

    @action(methods=['delete'], detail=False, url_path='deleteTopic')
    def deleteTopic(self, request):
        ids = request.data.get('ids', [])  # 获取请求中的ids，如果没有则默认为空列表
        print(ids)
        if not ids:
            return Response({'code': 1, 'message': '请选择要删除的帖子'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            deleted_count, _ = Topic.objects.filter(id__in=ids).delete()  # 执行批量删除，并获取删除的数量
            return Response({
                'code': 0,
                'message': f'成功删除了{deleted_count}个帖子',
                'data': TopicSerializer(self.get_queryset(), many=True).data
            })
        except Exception as e:
            return Response({'code': 2, 'message': f'删除帖子失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['post'], detail=False, url_path='addTopic')
    def addTopic(self, request):
        serializer = TopicSerializer(data=request.data)
        print(serializer)
        if serializer.is_valid():
            print(12)
            topic = serializer.save()
            return Response({
                'code': 0,
                'message': '新增帖子成功',
                'data': TopicSerializer(topic).data
            })
        return Response({'code': 1, 'message': '参数错误', 'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

    @action(methods=['post'], detail=False, url_path='adminChangeTopic')
    def admin_change_topic(self, request):
        # 从请求数据中获取t_id, t_kind和t_recommend
        t_id = request.data.get('id')
        t_kind = request.data.get('t_kind')
        t_recommend = request.data.get('recommend')

        # 确保t_id和t_recommend存在
        if t_id is None or t_recommend is None:
            return Response({'code': 1, 'message': '参数错误，缺少t_id或t_recommend'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 获取帖子实例
            topic = Topic.objects.get(id=t_id)
        except Topic.DoesNotExist:
            return Response({'code': 1, 'message': '帖子不存在'}, status=status.HTTP_404_NOT_FOUND)

        # 更新帖子推荐状态
        topic.recommend = t_recommend
        topic.save()

        # 序列化更新后的帖子
        serializer = TopicSerializer(topic)

        # 返回更新后的帖子信息
        return Response({
            'code': 0,
            'message': '修改推荐状态成功',
            'data': serializer.data
        })
        

from .models import Announcement
from .serializers import AnnouncementSerializer

class AnnouncementViewSet(viewsets.ModelViewSet):
    queryset = Announcement.objects.all()
    serializer_class = AnnouncementSerializer

    @action(detail=False, methods=['get'], url_path='getAnnouncementList')
    def get_announcement_list(self, request):
        announcements = Announcement.objects.all()
        serializer = AnnouncementSerializer(announcements, many=True)
        print(serializer.data)
        return Response({
            "code": 0,
            "message": "获取公告列表成功",
            "data": serializer.data
        })

    @action(detail=False, methods=['post'], url_path='postAnnouncement')
    def post_announcement(self, request):
        # 从请求数据中获取用户ID和公告内容
        print(request.data)
        user_id = request.data.get('id')
        content = request.data.get('content')

        # 确保用户ID存在
        if not user_id:
            return Response({"code": 1, "message": "用户ID不能为空"}, status=status.HTTP_400_BAD_REQUEST)

        # 获取用户实例
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({"code": 1, "message": "用户不存在"}, status=status.HTTP_400_BAD_REQUEST)

        # 创建序列化器实例，并传入用户实例和公告内容
        serializer = AnnouncementSerializer(data={'a_uid': user.id, 'a_content': content})
        if serializer.is_valid():
            serializer.save()
            return Response({
                "code": 0,
                "message": "发布公告成功"
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['delete'], url_path='deleteAnnouncement')
    def delete_announcement(self, request):
        print(request.query_params)
        id = request.query_params.get('id')
        if not id:
            return Response({
                "code": 1,
                "message": "请选择要删除的公告"
            }, status=status.HTTP_400_BAD_REQUEST)
        if not Announcement.objects.filter(id=id).exists():
            return Response({
                "code": 1,
                "message": "公告不存在"
            }, status=status.HTTP_400_BAD_REQUEST)
        announcement = Announcement.objects.get(id=id)
        announcement.delete()
        return Response({
            "code": 0,
            "message": "删除公告成功"
        })
